
package com.health.service.impl;
import com.health.config.JwtUtil;
import com.health.dao.DoctorMapper;
import com.health.dao.PatientMapper;
import com.health.dao.UserMapper;
import com.health.pojo.dto.DoctorDTO;
import com.health.pojo.dto.PatientDTO;
import com.health.pojo.dto.UserDTO;
import com.health.pojo.dto.UserInformation;
import com.health.pojo.query.UserQuery;
import com.health.service.UserService;
import java.lang.Boolean;
import java.lang.Integer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.health.exception.BusinessException;
import com.health.pojo.domain.DoctorDO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.health.pojo.domain.UserDO;

import java.util.HashMap;
import java.util.Map;
import com.health.pojo.domain.PatientDO;
import com.health.constant.ResultCodeConstant;
import java.util.Date;
import java.util.List;

/**
 * 用户管理的实现
 *
 * @author WUYU_MIN
 * @date 2025-04-29 23:51:18
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private PatientMapper patientMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private DoctorMapper doctorMapper;
    static private int id;

    @Override
    public Integer registerUser(UserDTO userDTO) {
        // 验证手机号是否已注册
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", userDTO.getPhone());
        UserDO existingUser = userMapper.selectOne(queryWrapper);
        if (existingUser != null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        // 插入主表users
        UserDO userDO = new UserDO();
        userDO.setPhone(userDTO.getPhone());
        userDO.setEmail(userDTO.getEmail());
        userDO.setPassword(userDTO.getPassword());
        userDO.setCoreRole(userDTO.getCoreRole());
        userDO.setCreatedAt(new Date());
        userDO.setUpdatedAt(new Date());
        userMapper.insert(userDO);

        UserDO existingUser2 = userMapper.selectOne(queryWrapper);
        id = existingUser2.getUserId();
        return id;
    }

    @Override
    public Boolean registerPatient(PatientDTO patientDTO) {
        PatientDO patientDO = new PatientDO();
        patientDO.setUserId(patientDTO.getUserId());
        patientDO.setName(patientDTO.getName());
        patientDO.setGender(patientDTO.getGender());
        patientDO.setDateOfBirth(patientDTO.getDateOfBirth());
        patientDO.setAge(patientDTO.getAge());
        patientDO.setEmergencyContact(patientDTO.getEmergencyContact());
        patientDO.setInsuranceCardNumber(patientDTO.getInsuranceCardNumber());
        patientDO.setCreatedAt(new Date());
        patientDO.setUpdatedAt(new Date());
        patientMapper.insert(patientDO);
        return true;
    }

    @Override
    public Boolean registerDoctor(DoctorDTO doctorDTO) {
        DoctorDO doctorDO = new DoctorDO();
        doctorDO.setUserId(doctorDTO.getUserId());
        doctorDO.setDoctorName(doctorDTO.getName());
        doctorDO.setLicenseNumber(doctorDTO.getMedicalLicenseNumber());
        doctorDO.setSpecialty(doctorDTO.getSpecialty());
        doctorDO.setHospital(doctorDTO.getHospital());
        doctorDO.setIntroduction(doctorDTO.getIntroduction());
        doctorDO.setCreatedAt(new Date());
        doctorDO.setUpdatedAt(new Date());
        doctorMapper.insert(doctorDO);
        return true;
    }

    @Override
    public String loginUser(UserDTO userDTO) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", userDTO.getPhone());
        // queryWrapper.eq("password", userDTO.getPassword());
        UserDO userDO = userMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        updateUserByPhone(userDTO.getPhone(),1);

        // 这里假设将用户 ID 作为 Token 的 subject，可以根据实际需求调整
        String token = JwtUtil.generateToken(userDO.getUserId().toString(), 3600000); // 过期时间为 1 小时

        return token;
    }

    @Override
    public Boolean logOff(String phone) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        UserDO userDO = userMapper.selectOne(queryWrapper);

        if (userDO == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        updateUserByPhone(phone,0);
        return true;
    }

    @Override
    public Integer getUserOnlineStatus(Integer userId) {
        System.out.println("id :" + userId);
        UserDO userDO = userMapper.selectById(userId);
        if (userDO == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        return userDO.getOnlineStatus();
    }

    @Override
    public Boolean deleteUser(UserDTO userDTO) {
        UserDO userDO = userMapper.selectById(userDTO.getUserId());
        if (userDO == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        // 软删除主表users中的用户信息
        userDO.setDeletedTime(new Date());
        userMapper.updateById(userDO);
        // 软删除详情表doctors或patients中的用户信息
        if ("patient".equals(userDO.getCoreRole())) {
            PatientDO patientDO = patientMapper.selectById(userDO.getUserId());
            if (patientDO != null) {
                patientDO.setDeletedTime(new Date());
                patientMapper.updateById(patientDO);
            }
        } else if ("doctor".equals(userDO.getCoreRole())) {
            DoctorDO doctorDO = doctorMapper.selectById(userDO.getUserId());
            if (doctorDO != null) {
                doctorDO.setDeletedTime(new Date());
                doctorMapper.updateById(doctorDO);
            }
        }
        return true;
    }



    @Override
    public List<PatientDO> queryPatientsByName(String name) {
        if (name == null || name.isEmpty()) {
            return patientMapper.selectList(null);
        }
        QueryWrapper<PatientDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("name", name);
        return patientMapper.selectList(queryWrapper);
    }

    @Override
    public List<DoctorDO> queryDoctorsByName(String name) {
        if (name == null || name.isEmpty()) {
            return doctorMapper.selectList(null);
        }
        QueryWrapper<DoctorDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("doctor_name", name);
        return doctorMapper.selectList(queryWrapper);
    }

    @Override
    public Boolean updatePatient(PatientDTO patientDTO) {
        QueryWrapper<PatientDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", patientDTO.getUserId());
        PatientDO patientDO = patientMapper.selectOne(queryWrapper);
        if (patientDO == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        patientDO.setName(patientDTO.getName());
        patientDO.setGender(patientDTO.getGender());
        patientDO.setDeletedTime(patientDTO.getDateOfBirth());
        patientDO.setAge(patientDTO.getUserId());
        patientDO.setEmergencyContact(patientDTO.getEmergencyContact());
        patientDO.setInsuranceCardNumber(patientDTO.getInsuranceCardNumber());
        patientDO.setUpdatedAt(new Date());
        patientMapper.updateById(patientDO);
        return true;
    }

    @Override
    public Boolean updateDoctor(DoctorDTO doctorDTO) {
        QueryWrapper<DoctorDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", doctorDTO.getUserId());
        DoctorDO doctorDO = doctorMapper.selectOne(queryWrapper);
        if (doctorDO == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        doctorDO.setDoctorName(doctorDTO.getName());
        doctorDO.setLicenseNumber(doctorDTO.getMedicalLicenseNumber());
        doctorDO.setSpecialty(doctorDTO.getSpecialty());
        doctorDO.setHospital(doctorDTO.getHospital());
        doctorDO.setIntroduction(doctorDTO.getIntroduction());
        doctorDO.setUpdatedAt(new Date());
        doctorMapper.updateById(doctorDO);
        return true;
    }

    @Override
    public UserInformation selectUser(UserDTO userDTO) {
        System.out.println(userDTO);
        UserInformation userInformation = new UserInformation();

        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userDTO.getUserId());
        UserDO userDO = userMapper.selectOne(queryWrapper);

        if (userDO != null) {
            userInformation.setUserDO(userDO);
            String coreRole = userInformation.getUserDO().getCoreRole();
            if (coreRole != null) {
                if (coreRole.equals("doctor")) {
                    userInformation.setDoctorDO(doctorMapper.selectById(userDTO.getUserId()));
                } else if (coreRole.equals("patient")) {
                    userInformation.setPatientDO(patientMapper.selectById(userDTO.getUserId()));
                }
            }
        }
        return userInformation;
    }

    @Override
    public Boolean updateUser(UserDTO userDTO) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userDTO.getUserId());
        UserDO userDO = userMapper.selectOne(queryWrapper);

        if (userDO == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        userDO.setPhone(userDTO.getPhone());
        userDO.setEmail(userDTO.getEmail());
        userDO.setUpdatedAt(new Date());
        userMapper.updateById(userDO);
        return true;

    }

    public Boolean updateUserByPhone(String phone, int status) {
        QueryWrapper<UserDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        UserDO userDO = userMapper.selectOne(queryWrapper);
        if (userDO == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }
        userDO.setOnlineStatus(status); // 设置online_status为true
        userDO.setUpdatedAt(new Date());
        userMapper.updateById(userDO);
        return true;
    }
}
